package com.briup.es.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.response.ResultCode;
import com.briup.es.constant.OrderStatus;
import com.briup.es.domain.bean.Order;
import com.briup.es.domain.dto.OrderPayDTO;
import com.briup.es.domain.dto.PaySuccessDTO;
import com.briup.es.property.AlipayProperty;
import com.briup.es.service.OrderPayService;
import com.briup.es.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderPayServiceImpl implements OrderPayService {

    private final OrderService orderService;
    private final AlipayProperty alipayConfig;

    @Override
    public String orderPay(OrderPayDTO orderPayDTO) {
        // 完成校验工作
        Order order = check(orderPayDTO.getOrderId());

        // 校验成功后，对订单进行支付（使用支付宝沙箱）
        // 新建alipay客户端
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGateway(),
                alipayConfig.getAppId(), alipayConfig.getSecretKey(), "json",
                alipayConfig.getCharset(), alipayConfig.getPublicKey(), "RSA2");

        // 实例化具体API对应的request类，用于向支付宝沙箱服务器发送请求
        // 创建网页的支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 给请求设置必要的参数，如支付的订单id，支付的金额，支付的商品备注等内容
        // 需要通过AlipayTradePayModel实现设置
        AlipayTradePayModel payModel = new AlipayTradePayModel();
        // 订单编号
        payModel.setOutTradeNo(order.getId());
        // 订单金额
        Double totalPrice = orderPayDTO.getTotalPrice();
        payModel.setTotalAmount(totalPrice == 0.0 ? "0.01" : totalPrice.toString());
        // 订单名称
        payModel.setSubject("购买图书");
        // 产品码
        payModel.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 将数据模型设置到请求中，即和请求进行绑定
        request.setBizModel(payModel);
        // 设置请求成功后的回调地址
        request.setReturnUrl(orderPayDTO.getPathUrl());

        // 发送请求
        String result = "";
        try {
            result = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            log.error("支付失败，失败的原因为:", e);
        }

        // 将结果返回给前端，由前端进行解析处理
        return result;
    }

    @Override
    public void paySuccess(PaySuccessDTO paySuccessDTO) {
        Order detailVO = check(paySuccessDTO.getOrderId());
        // 转换为Order类对象
        Order order = Order.builder()
                .id(detailVO.getId())
                .status(OrderStatus.PAYED.getCode())
                .payDate(paySuccessDTO.getPayDate())
                .payWay(paySuccessDTO.getPayWay())
                .build();
        // 修改数据
        orderService.updateById(order);
    }

    private Order check(String orderId) {
        // 首先得明确该订单还存在
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new ServiceException(ResultCode.ORDER_IS_NOT_EXISTS);
        }

        // 判断状态是否为可支付状态，即当前订单是否未支付
        if (!Objects.equals(OrderStatus.NOT_PAY.getCode(), order.getStatus())) {
            throw new ServiceException(ResultCode.ORDER_CAN_NOT_PAY);
        }

        return order;
    }
}
